//
//  JBWNetworkTools.swift
//  
//
//  Created by 季伯文 on 2017/7/1.
//
//

import UIKit
import AFNetworking

//请求方式get post枚举
enum JBWNetworkToolsType:String {
    case get = "get"
    case post = "post"
}
class JBWNetworkTools: AFHTTPSessionManager {
    
    //全局访问点
    static let share:JBWNetworkTools = {
        let tools = JBWNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    func request(type: JBWNetworkToolsType,urlString: String, parameters:Any?, success: @escaping(Any?) ->(), failure:@escaping (Error)->()){

    
    if type == .get {
        get(urlString, parameters: parameters, progress: nil, success:{
         (_,response)in
        success(response)
        }, failure:  { (_, error)in
        failure(error)
    })
    } else {
    
        post(urlString, parameters: parameters, progress: nil, success:{
        (_,response)in
        success(response)
        }, failure:  { (_, error)in
        failure(error)
        })
    }
    }
}

//OAuth需要的网络接口
extension JBWNetworkTools {
    
    //请求token
    func oauthLoadUserAccount(code: String,success: @escaping (Any?) -> (), failure: @escaping (Error) -> ()){
        //请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let params = ["client_id": JBWAPPKEY,
                      "client_secret": JBWAPPSECRET,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": JBWREDIRECT_URI
        ]
        request(type: JBWNetworkToolsType.post, urlString: urlString, parameters: params, success: success, failure: failure)
}
    
    // 请求个人信息数据
    func oauthLoadUserInfo(userAccountModel: JBWUserAccountModel,success: @escaping (Any?) -> (), failure: @escaping (Error) -> ()){
        // 请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token": userAccountModel.access_token,
            "uid": userAccountModel.uid]
        //发送网络请求
        request(type: JBWNetworkToolsType.get, urlString: urlString, parameters: params, success: success, failure: failure)
}

}


//请求网络数据接口
extension JBWNetworkTools {
    func homeLoadData(since_id:Int64, max_id:Int64 ,success:@escaping (Any?)->(), failure:@escaping (Error)->()){
    // 请求地址
    let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
    // 请求参数
    let params = ["access_token": JBWOAuthViewModel.share.accessToken,
        "since_id": "\(since_id)",
        "max_id": "\(max_id)"]
    // 发送请求
    request(type: .get, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}
